<template>
  <textarea :ref="($event) => setRef($event)" :id="props.editorId"></textarea>
</template>
<script setup lang="ts" name="TpEditor">
/* Import TinyMCE */
import tinymce, { Editor } from "tinymce";
import "./index";
const { proxy } = getCurrentInstance() as any;
const props = withDefaults(defineProps<{ editorId: string }>(), {
  editorId: "",
});
const emit = defineEmits(["setup", "init-callback"]);
let editorIdRef = ref();
const setRef = (_e: any) => {
  editorIdRef.value = _e;
};
function render() {
  // 订阅者B订阅全局Subject
  proxy.$subject.subscribe({
    next: ({ height }: any) => {
      tinymce.init({
        id: props.editorId,
        selector: `textarea#${props.editorId}`,
        "api-key": "7jesosfuchdiemd04dge05lsgj0t7m3th32yr2uru3qp2rxz",
        contextmenu:
          "copy paste | image inserttable | cell row column deletetable", // 右键菜单配置
        autosave_ask_before_unload: false,
        plugins: "advlist code emoticons link lists table importcss",
        toolbar: "bold italic | bullist numlist | link emoticons",
        skin_url: "default",
        content_css: "tinymce/skins/ui/oxide/content.css",
        width: "100%",
        height: height,
        font_size_legacy_values: "16px",
        font_size_input_default_unit: "16px",
        // importcss_append: true,
        inline_styles: true,
        formats: {},
        font_size_formats:
          "10px 11px 12px 14px 16px 18px 20px 22px 24px 26px 28px 32px 34px 36px",
        font_size_style_values: "16px",
        language: "zh-Hans",
        content_style:
          ".mce-offscreen-selection { display: none; } p {font-size: 20px}",
        statusbar: false, // 隐藏状态栏 不显示左下角的标签信息
        resize: false, // 编辑器窗口大小不允许拖拽
        promotion: false, // 去掉右上角Upgrade按钮
        branding: false, // 去掉右下角商标
        setup: (_editor) => {
          emit("setup", _editor);
          onEditorInit(_editor);
        },
      });
    },
  });
}
function onEditorInit(_editor: Editor) {
  _editor.on("init", (_) => {
    _editor.resetContent();
    emit("init-callback", _editor);
    // _editor.dom.select("p") select p| p,div|... *
    _editor.dom.setStyles(_editor.dom.select("p"), { margin: "2px", 'font-size': '16px' });
    _editor.on("keydown", ({keyCode}: any) => {
      if (keyCode == 8 || keyCode == 46) {
        if (!_editor.selection.getEnd().innerHTML) {
          _editor.dom.setStyles(_editor.dom.select("p"), { margin: "2px", 'font-size': '16px' });
        }
      }
    });
  });
}
// 初始化TinyMCE并插入内容
onMounted(() => {
  const editor = tinymce.get(props.editorId);
  // 如果存在则销毁重新渲染否则会偶现渲染不成功
  if (editor) {
    editor.destroy();
  }
  render();
});
onBeforeUnmount(() => {
  const editor = tinymce.get(props.editorId);
  if (editor) {
    editor.destroy();
  }
});
</script>

<style lang="scss" scoped></style>
